package com.ysd.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ysd.entity.Member;
import com.ysd.entity.MemberSearch;
import com.ysd.repository.MemberRepository;
import com.ysd.util.Result;
import com.ysd.util.WebExcelUtil;

import cn.afterturn.easypoi.excel.entity.ImportParams;

@RestController
public class MemberController {
	@Autowired
	private MemberRepository mRepository;
	
	//多条件分页查询全部
	@RequestMapping("getAll")
	public Object getAll(MemberSearch ms,int page, int limit) {
		Specification<Member> s = getMemberSpec(ms);
		List<Member> m = mRepository.findAll(s);
		Pageable pagea= new PageRequest(page-1, limit);
		Page<Member> pm = mRepository.findAll(s, pagea);
		if (m!=null) {
			return Result.toClient("0", "成功", m.size(), pm.getContent());
		} else {
			return Result.toClient("1", "失败", m.size(), pm.getContent());
		}
		
	}
	
	//多条件拼接
	public Specification<Member> getMemberSpec(MemberSearch ms){
		return new Specification<Member>() {

			@Override
			public Predicate toPredicate(Root<Member> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate p = cb.conjunction();
				List<Expression<Boolean>> list = p.getExpressions();
				if (ms.getName() != null && !ms.getName().equals("")) {
					list.add(cb.like(root.get("name"), "%"+ms.getName()+"%"));
				}
				if (ms.getCard_no() != null && !ms.getCard_no().equals("")) {
					list.add(cb.equal(root.get("card_no"), ms.getCard_no()));
				}
				if (ms.getDepartment() != null && !ms.getDepartment().equals("")) {
					list.add(cb.equal(root.get("department"), ms.getDepartment()));
				}
				if (ms.getProfession() != null && !ms.getProfession().equals("")) {
					list.add(cb.equal(root.get("profession"), ms.getProfession()));
				}
				if (ms.getGrade() != null && !ms.getGrade().equals("")) {
					list.add(cb.equal(root.get("grade"), ms.getGrade()));
				}
				if (ms.getPhone() != null && !ms.getPhone().equals("")) {
					list.add(cb.like(root.get("phone"), "%"+ms.getPhone()+"%"));
				}
				if (ms.getCategory()!=null) {
					list.add(cb.equal(root.get("category"), ms.getCategory()));
				}
				if (ms.getBeginRegdate() != null && !ms.getBeginRegdate().equals("")) {
					list.add(cb.greaterThanOrEqualTo(root.get("regdate"), ms.getBeginRegdate()));
				}
				if (ms.getEndRegdate()!=null && !ms.getEndRegdate().equals("")) {
					list.add(cb.lessThanOrEqualTo(root.get("regdate"), ms.getEndRegdate()));
				}
				if (ms.getStatus() != null && !ms.getStatus().equals("")) {
					list.add(cb.equal(root.get("status"), ms.getStatus()));
				}
				
				return p;
			}
		};
	}
	
	//添加
	@RequestMapping("addMenber")
	public Object addMenber(Member m) {
		Member mb = mRepository.save(m);
		if (mb!=null) {
			return Result.toClient("0", "添加成功", "");
		} else {
			return Result.toClient("1", "添加失败", "");
		}
	}
	
	//删除
	@RequestMapping("delMenber")
	public Object delMenber(int id) {
		try {
			mRepository.delete(id);
			return Result.toClient("0", "删除成功","");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.toClient("1", "删除失败","");
		}
	}
	
	//批量删除
	@RequestMapping("delMenbers")
	public Object delMenbers(String ids) {
		String[] stuList = ids.split(",");
		List idaList = new ArrayList();
		for(String stId : stuList){
			idaList.add(new Integer(stId));
		}
		try {
			mRepository.deleMemberByIds(idaList);
			return Result.toClient("0","成功",null);
		} catch (Exception e) {
			// TODO: handle exception
			return Result.toClient("1","失败",null);
		}
	}
	
	
	
	//修改
	@RequestMapping("updateMenber")
	public Object updateMenber(int id,String name,String sex,Integer category,String department,String profession,String grade,String phone,String remark) {
		int n = mRepository.updateMember(id, name, sex, category, department, profession, grade, phone, remark);
		if (n > 0) {
			return Result.toClient("0", "修改成功","");
		} else {
			return Result.toClient("1", "修改失败","");
		}
	}
	
	//通过ID修改状态(重置)
	@RequestMapping("updateStatusOutById")
	public Object updateStatusOutById(int id) {
		int n = mRepository.updateStatusOutById(id);
		if (n > 0) {
			return Result.toClient("0", "状态修改成功","");
		} else {
			return Result.toClient("1", "状态修改失败","");
		}
	}
	
	//通过ID修改状态
	@RequestMapping("updateStatusInById")
	public Object updateStatusInById(String status, int id) {
		int n = mRepository.updateStatusInById(status, id);
		if (n > 0) {
			return Result.toClient("0", "状态修改成功","");
		} else {
			return Result.toClient("1", "状态修改失败","");
		}
	}
	
	//通过学号查询输入的学号是否正确
	@RequestMapping("selMemberByCard_no")
	public Object selMemberByCard_no(String card_no) {
		Member m = mRepository.selMemberByCard_no(card_no);
		if (m != null) {
			return Result.toClient("0", "查询成功", m);
		} else {
			return Result.toClient("1", "查询失败", null);
		}
	}
	
	//通过学号查询输入的学号是否正确
	@RequestMapping("selMemberByCard_noAndCard")
	public Object selMemberByCard_noAndCard(String card_no,String card) {
		Member m = mRepository.selMemberByCard(card_no);
		System.out.println("card_no"+card_no);
		System.out.println("card"+card);
		if (m != null) {
			Member mb = mRepository.selMemberByCard_no(card);
			if (mb != null) {
				return Result.toClient("0", "学号重复", null);
			} else {
				return Result.toClient("0", "身份证号重复", null);
			}
		} else {
			return Result.toClient("1", "可以添加", null);
		}
	}
	
		
	//通过学号查询输入的学号是否正确
	@RequestMapping("selMemberByCard_nos")
	public Object selMemberByCard_nos(String card_no) {
		Member m = mRepository.selMemberByCard_no(card_no);
		if (m != null) {
			String sta = m.getStatus();
			System.out.println(sta);
			if (sta.equals("0")) {
				return Result.toClient("0", "可以进入", "");
			} else {
				return Result.toClient("1", "该用户已经在资源室", null);
			}
		} else {
			return Result.toClient("1", "查询失败", null);
		}
	}
		
	//POI导出功能
	@RequestMapping("export")
	public void export(HttpServletResponse response) {
		List<Member> list = mRepository.findAll();
		System.out.println("export"+list);
		WebExcelUtil.exportExcel(list, "会员表", "sheet1", Member.class, "cfqtable.xls", response);
			
	}
	//POI导入功能
	@PostMapping("importMe")
	public Object importMe(MultipartFile file, HttpServletRequest request) throws Exception {
		System.out.println(file);
		ImportParams params = new ImportParams();
		params.setTitleRows(0);
		params.setHeadRows(1);
		List<Member> list;
		try {
			// excel的数据
			list = WebExcelUtil.importExcel(file, 1, 1, Member.class);
			for (Member mer : list) {
				Member meb = new Member();
				meb.setId(null);
				meb.setCard_no(mer.getCard_no());
				meb.setName(mer.getName());
				meb.setSex(mer.getSex());
				meb.setCategory(mer.getCategory());
				meb.setCard(mer.getCard());
				meb.setDepartment(mer.getDepartment());
				meb.setProfession(mer.getProfession());
				meb.setPhone(mer.getPhone());
				meb.setGrade(mer.getGrade());
				meb.setRegdate(mer.getRegdate());
				meb.setStatus(mer.getStatus());

				mRepository.InsertMember(meb);// 调用了一个新增的方法
				System.out.println(meb);
			}

			System.out.println(list);
			return "导入成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "导入失败";
		}
	}
}
